<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Location, Warning, Tools, User, Timer, Check, ArrowLeft, Refresh, Calendar, Search } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const currentUser = userStore.userInfo.username

// 工作报告数据
const completedTasks = ref([])
const loading = ref(true)

// 统计数据
const statistics = reactive({
  totalCompleted: 0,
  thisMonthCompleted: 0,
  averageTimeToComplete: 0, // 平均处理时间（天）
  byDamageType: {} // 按损坏类型统计
})

// 筛选表单
const filterForm = reactive({
  dateRange: null,
  roadName: '',
  damageType: '',
  maintainMethod: ''
})

// 维护方法选项
const maintainMethodOptions = [
  { value: '沥青修补', label: '沥青修补' },
  { value: '混凝土修复', label: '混凝土修复' },
  { value: '路面重铺', label: '路面重铺' },
  { value: '裂缝灌缝', label: '裂缝灌缝' },
  { value: '井盖更换', label: '井盖更换' },
  { value: '标线重绘', label: '标线重绘' },
  { value: '其他', label: '其他' }
]

// 损坏类型选项
const damageTypeOptions = [
  { value: '路面裂缝', label: '路面裂缝' },
  { value: '坑洼', label: '坑洼' },
  { value: '井盖损坏', label: '井盖损坏' },
  { value: '路面沉降', label: '路面沉降' },
  { value: '标线磨损', label: '标线磨损' },
  { value: '其他', label: '其他' }
]

// 筛选后的任务列表
const filteredTasks = computed(() => {
  let result = [...completedTasks.value]
  
  // 按日期范围筛选
  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    const startDate = new Date(filterForm.dateRange[0])
    const endDate = new Date(filterForm.dateRange[1])
    endDate.setHours(23, 59, 59, 999) // 设置为当天结束时间
    
    result = result.filter(task => {
      const maintainDate = new Date(task.maintainTime)
      return maintainDate >= startDate && maintainDate <= endDate
    })
  }
  
  // 按道路名称筛选
  if (filterForm.roadName) {
    result = result.filter(task => 
      task.roadName && task.roadName.includes(filterForm.roadName)
    )
  }
  
  // 按损坏类型筛选
  if (filterForm.damageType) {
    result = result.filter(task => 
      task.damageType === filterForm.damageType
    )
  }
  
  // 按维护方法筛选
  if (filterForm.maintainMethod) {
    result = result.filter(task => 
      task.maintainMethod === filterForm.maintainMethod
    )
  }
  
  return result
})

// 重置筛选条件
const resetFilter = () => {
  filterForm.dateRange = null
  filterForm.roadName = ''
  filterForm.damageType = ''
  filterForm.maintainMethod = ''
}

// 加载已完成的养护任务
const loadCompletedTasks = async () => {
  loading.value = true
  try {
    // 创建道路损坏要素图层
    const roadDamageLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/gcgG56UMRGbwuqfF/arcgis/rest/services/RoadDamageSegment/FeatureServer/0',
      outFields: ['*']
    })

    // 查询当前养护人员已完成的任务
    const query = roadDamageLayer.createQuery()
    query.where = `maintainer = '${currentUser}' AND status = '已完成'` // 只查询当前用户已完成的任务
    query.outFields = ["*"]
    query.returnGeometry = false

    const results = await roadDamageLayer.queryFeatures(query)
    const features = results.features

    // 转换为任务列表格式
    completedTasks.value = features.map(feature => {
      return {
        id: feature.attributes.OBJECTID,
        roadName: feature.attributes.roadName || '未知道路',
        damageType: feature.attributes.damageType || '未知类型',
        severityLevel: feature.attributes.severityLevel || '未知',
        reportTime: feature.attributes.reportTime || '',
        maintainTime: feature.attributes.maintainTime || '',
        maintainMethod: feature.attributes.maintainMethod || '',
        remark: feature.attributes.remark || '',
        description: feature.attributes.description || ''
      }
    })

    // 计算统计数据
    calculateStatistics()

    loading.value = false
  } catch (error) {
    console.error('加载已完成任务失败', error)
    ElMessage.error('加载数据失败，请稍后重试')
    loading.value = false
  }
}

// 计算统计数据
const calculateStatistics = () => {
  const tasks = completedTasks.value
  
  // 总完成数量
  statistics.totalCompleted = tasks.length
  
  // 本月完成数量
  const now = new Date()
  const thisMonth = now.getMonth()
  const thisYear = now.getFullYear()
  statistics.thisMonthCompleted = tasks.filter(task => {
    if (!task.maintainTime) return false
    const maintainDate = new Date(task.maintainTime)
    return maintainDate.getMonth() === thisMonth && maintainDate.getFullYear() === thisYear
  }).length
  
  // 按损坏类型统计
  const typeCount = {}
  tasks.forEach(task => {
    const type = task.damageType || '未知类型'
    typeCount[type] = (typeCount[type] || 0) + 1
  })
  statistics.byDamageType = typeCount
  
  // 计算平均处理时间
  let totalDays = 0
  let validTaskCount = 0
  
  tasks.forEach(task => {
    if (task.reportTime && task.maintainTime) {
      const reportDate = new Date(task.reportTime)
      const maintainDate = new Date(task.maintainTime)
      const days = Math.round((maintainDate.getTime() - reportDate.getTime()) / (1000 * 60 * 60 * 24))
      if (days >= 0) {
        totalDays += days
        validTaskCount++
      }
    }
  })
  
  statistics.averageTimeToComplete = validTaskCount > 0 ? Math.round(totalDays / validTaskCount * 10) / 10 : 0
}

// 查看任务详情
const viewTaskDetail = (row) => {
  ElMessageBox.alert(
    `<div class="task-detail">
      <p><strong>道路名称：</strong>${row.roadName}</p>
      <p><strong>损坏类型：</strong>${row.damageType}</p>
      <p><strong>严重程度：</strong>${row.severityLevel}</p>
      <p><strong>报告时间：</strong>${row.reportTime}</p>
      <p><strong>完成时间：</strong>${row.maintainTime}</p>
      <p><strong>维护方法：</strong>${row.maintainMethod}</p>
      <p><strong>问题描述：</strong>${row.description}</p>
      <p><strong>备注：</strong>${row.remark || '无'}</p>
    </div>`,
    '任务详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    }
  )
}

// 获取严重程度对应的标签类型
const getSeverityType = (severity) => {
  switch (severity) {
    case '危险':
      return 'danger'
    case '严重':
      return 'warning'
    case '中等':
      return 'info'
    case '轻微':
      return 'success'
    default:
      return ''
  }
}

// 返回养护页面
const goToMaintenance = () => {
  router.push('/maintenance')
}

// 页面加载时获取数据
onMounted(() => {
  loadCompletedTasks()
})
</script>

<template>
  <div class="maintainer-reports-container">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goToMaintenance" plain>
          <el-icon><arrow-left /></el-icon> 返回养护页面
        </el-button>
      </div>
      <div class="header-title">
        <h1>工作报告</h1>
        <p>查看您已完成的养护任务和工作统计</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="loadCompletedTasks">
          <el-icon><refresh /></el-icon> 刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon><Check /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.totalCompleted }}</div>
              <div class="stat-label">总完成任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon><Calendar /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.thisMonthCompleted }}</div>
              <div class="stat-label">本月完成</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon><Timer /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.averageTimeToComplete }}</div>
              <div class="stat-label">平均处理天数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon><Tools /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ Object.keys(statistics.byDamageType).length }}</div>
              <div class="stat-label">处理损坏类型</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选表单 -->
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <el-icon><Search /></el-icon>
          <span>筛选条件</span>
        </div>
      </template>
      
      <el-form :model="filterForm" label-width="100px" inline>
        <el-form-item label="完成日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="道路名称">
          <el-input v-model="filterForm.roadName" placeholder="输入道路名称" clearable />
        </el-form-item>
        
        <el-form-item label="损坏类型">
          <el-select v-model="filterForm.damageType" placeholder="选择损坏类型" clearable>
            <el-option
              v-for="item in damageTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="维护方法">
          <el-select v-model="filterForm.maintainMethod" placeholder="选择维护方法" clearable>
            <el-option
              v-for="item in maintainMethodOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="resetFilter">重置筛选</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="tasks-card">
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span>已完成任务列表</span>
          <span class="task-count">共 {{ filteredTasks.length }} 条记录</span>
        </div>
      </template>
      
      <el-table
        :data="filteredTasks"
        style="width: 100%"
        v-loading="loading"
        @row-click="viewTaskDetail"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="roadName" label="道路名称" min-width="120" />
        <el-table-column prop="damageType" label="损坏类型" width="120" />
        <el-table-column prop="severityLevel" label="严重程度" width="100">
          <template #default="scope">
            <el-tag
              :type="getSeverityType(scope.row.severityLevel)"
              size="small"
            >
              {{ scope.row.severityLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="maintainMethod" label="维护方法" width="120" />
        <el-table-column prop="reportTime" label="报告时间" width="180" />
        <el-table-column prop="maintainTime" label="完成时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" plain @click.stop="viewTaskDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <template #empty>
        <el-empty v-if="!loading" description="暂无已完成的任务" />
      </template>
    </el-card>
  </div>
</template>

<style scoped>
.maintainer-reports-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  text-align: center;
}

.header-title h1 {
  margin: 0;
  font-size: 24px;
}

.header-title p {
  margin: 5px 0 0;
  color: #666;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-content .el-icon {
  font-size: 48px;
  margin-right: 20px;
  color: #409EFF;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
}

.card-header .el-icon {
  margin-right: 10px;
  font-size: 18px;
}

.task-count {
  margin-left: auto;
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

.tasks-card {
  margin-bottom: 20px;
}

:deep(.task-detail) {
  text-align: left;
}

:deep(.task-detail p) {
  margin: 8px 0;
}
</style>
